var app = getApp();
var plugin = requirePlugin("ihearing-eval");// 智聆口语测评（腾讯免费）
let plugin4SEO = requirePlugin("myPlugin");//  智聆语音测评（腾讯付费）
let manager = plugin.getRecordRecognitionManager();
const FN = require('../../utils/public');
import commonAPI from '../../api/api'
var ba = wx.getBackgroundAudioManager();
import util from '../../utils/util.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    options: {}, // 保存传过来的参数，防止用户第一次进入，授权后，导致options参数丢失。
    followUpReadingDetailObj: {},
    evadingAudit: {},// 隐藏页面控制
    priTmplIdArr: [],// 订阅消息id
    words: [],
    errorWords: [],
    scoreArr: [],
    currentItem: 0,
    btnimgarr: [0, 0, 0],
    touchStartTime: 0,
    playGif: "horn.png",
    usplayGif: "horn.png",
    translationResultWrap: 'none',
    getIntoType: 'other',// 进入页面方式
    translationResult: {},// 翻译结果
    swiperIndex: 0,
    wordcount: 0,
    scoreDetail: {},
    stuWXinfo: {},
    page: 1,
    hasRepeated: true,
    repeating: false,
    integralObj:{},// 积分对象
    evaluationType: '1',// 口语测评模式，1：智聆口语测评（腾讯免费），2：智聆语音测评（腾讯付费），默认1
    tempFile: {},// 跟读者的音频临时路径
    pointsConfig4translateLowScoreWords: {},// 低分单词積分配置
    pointsConfig4AIErrorCorrection: {},// AI纠音積分配置
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.hideShareMenu(); // 禁止分享 
    this.getSubscribeMsg();// 订阅消息
    if (options.hasOwnProperty('scene')) {
      this.setData({
        options: options,        
      })
      that.intoPageType(options);
    } else {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('acceptDataFromOpenedPage', {});
      eventChannel.emit('someEvent', {});
      eventChannel.on('acceptDataFromOpenerPage', function (data) {
        that.setData({
          options: data,
          getIntoType:data.getIntoType
        });
        that.intoPageType(data);
      })
    }
    setTimeout(function(){
      that.setData({
        evadingAudit: app.globalData.evadingAudit
      });
    },1000)
    
    this.initOthderData();
  },

  /*
  1. 设置app屏幕的高度
  2. 获取微信小程序信息->设置当前纠音模型
  */
  initOthderData() {
    // 微信用户信息
    app.getMiniappInfo()// 小程序信息
    app.callback4MiniappInfo = miniappInfo => {
      const item = app.globalData.miniappInfo.pointsconfigList.find(item=>item.pointsConfigKey == 'translateLowScoreWords');
      const item4AIErrorCorrection = app.globalData.miniappInfo.pointsconfigList.find(item=>item.pointsConfigKey == 'AIErrorCorrection');
      this.setData({
        evaluationType: miniappInfo.miniappInfoModel,
        pointsConfig4translateLowScoreWords:item,// 单词翻译
        pointsConfig4AIErrorCorrection:item4AIErrorCorrection//  AI纠音
      })
    }
  },

  // 获取订阅消息
  getSubscribeMsg: function () {
    var that = this;
    commonAPI.getSubscribeMsg({ pageUrl: util.getCurrentPageUrl() }).then(res => {
      if (res.code == '200' && res.data.length > 0) {
        var arr = res.data[0].priTmplIdArr.split(",")
        that.setData({
          priTmplIdArr: arr
        })
      }
    })
  },

  // 订阅消息
  subscribeMsg() {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: that.data.priTmplIdArr,
      success(res) { },
      fail(res) { console.log("取消订阅", res) }
    })
  },

  // 翻译
  translation: function (e) {
    if(this.data.integralObj.integralNum < this.data.pointsConfig4translateLowScoreWords.pointsConfigValue || this.data.integralObj.integralNum==null){
      that.navigateToPointsPageForVideo(res.userInfo.integralObj.integralNum);
      return;
    }
    var that = this;
    var words = e.currentTarget.dataset.words
    wx.navigateTo({
      url: '../translationResult/translationResult?words=' + words + '&voiceSystemId=' + that.data.followUpReadingDetailObj.voiceSystemId
    })
  },

  // 听原音
  listenVoice: function (e) {
    var that = this,
      btnObjState = "btnimgarr[0]";
    const obj = that.data.followUpReadingDetailObj;
    that.setData({
      [btnObjState]: 1
    })
    this.subscribeMsg();
    if (obj.voiceFileType == '2') {
      this.playSMvoiceFile(obj);// 播放小音频
    } else {
      this.playVoiceByTimes(obj);// 播放时间段模式
    }
  },

  // 播放音频按照时间端，新方法
  playVoiceByTimes(obj) {
    var that = this;
    const bam = wx.getBackgroundAudioManager();
    const star = parseFloat(obj.timing);
    const end = parseFloat(obj.endTiming);
    bam.src = obj.voiceSystemURL
    bam.title = obj.booksName
    bam.epname = obj.bookChapteName// 专辑名，原生音频播放器中的分享功能，分享出去的卡片简介，也将使用该值
    bam.singer = obj.booksName
    bam.coverImgUrl = obj.voiceSystemImage
    bam.startTime = star;
    // bam.play();
    bam.onPlay(function () {
      setTimeout(() => {
        bam.stop();
        var btnObjState = "btnimgarr[0]";
        that.setData({
          [btnObjState]: 0
        })
      }, (end - star) * 1000);
    })
    bam.onError(function () {
      bam.stop()
      var btnObjState = "btnimgarr[0]";
      that.setData({
        [btnObjState]: 0
      })
    })

    // 暂停
    bam.onStop(function () {
      var btnObjState = "btnimgarr[0]";
      that.setData({
        [btnObjState]: 0
      })
    })

    // 播放结束
    bam.onEnded(() => {
      bam.stop()
      var btnObjState = "btnimgarr[0]";
      that.setData({
        [btnObjState]: 0
      })
    })
  },

  // 播放整段音频，小音频
  playSMvoiceFile(obj) {
    var that = this, btnObjState = "btnimgarr[0]";;
    ba.src = obj.voiceSystemURL;
    ba.title = obj.voiceToen;
    // ba.play();
    // 播放结束
    ba.onEnded(function () {
      that.setData({
        [btnObjState]: 0
      })
    })
    // 播放暫停
    ba.onPause(function () {
      that.setData({
        [btnObjState]: 0
      })
    })
  },

  // 暂停原文
  stopVoice: function (e) {
    var that = this;
    var btnObjState = "btnimgarr[0]";
    that.setData({
      [btnObjState]: 0
    })
    ba.pause();
  },

  // 按住
  starFollowup: function (e) {
    var that = this;
    that.setData({
      repeating: true
    })
    this.data.touchStartTime = e.timeStamp
    this.stopVoice();
  },

  // 松开
  endFollowup: function (e) {
    manager.stop();
    this.setData({
      repeating: false
    })
  },

  // 录音
  followup: function () {
    if (this.data.evaluationType == '1') {
      this.freeEvaluation()// 监听录音
      this.initStartOption4free();// 开始录音识别
    } else {
      this.initStartOption4SOE();// 开始录音识别
    }
  },

  // 智聆口语测评（免费模式）
  freeEvaluation() {
    var that = this;
    manager.onStart = function (res) { // 正常开始录音识别时会调用此事件
      console.log("成功开始录音识别", res);
    }
    // 识别结束事件
    manager.onStop = function (res) {
      if (res.duration < 500) {
        FN.Toast('录音时间过短')
        return;
      }
      if (res.result.words.length == 0) {
        FN.Toast('未检测到声音')
        return;
      }
      that.analysisTool(res);
      that.subVoiceInfo(); // 同步录音到服务器
      that.saveSignIn(); // 签到
    }
    manager.onError = function (res) { // 异常回调
      FN.Toast(res.msg);
      manager.stop();
      // 20802 小程序请求频率限制,
      if (res.retcode == 20802) {
        FN.Toast('AI测评打分高峰期');
        that.setData({
          evaluationType:'2'
        });
        that.updateAImodel();// 更改AI纠音模型
        that.initManagerModel();// 切换AI纠音模型
      }
    }
  },

  // 录音配置(soe模式)
  initStartOption4SOE() {
    const voiceToen = this.data.followUpReadingDetailObj.voiceToen;
    const options4SOE = {
      content: voiceToen,
      evalMode: this.getEvaluationMode(),// 0：词模式（中文评测模式下为文字模式），1：句子模式，2：段落模式，3：自由说模式，当为词模式评估时
      duration: 60000,
      scoreCoeff: 2.5, // [1.0 - 4.0] 范围内的浮点数，用于引擎评分的严格程度
      serverType: 0,// 评估语言，0：英文，1：中文。
      textMode: 0,// 输入文本模式，0: 普通文本，1: 音素结构文本      
    }
    manager.start(options4SOE); // 开始识别
  },

  // 录音配置(免費模式)
  initStartOption4free() {
    var that = this;
    const options = {
      duration: 60000,
      content: that.data.followUpReadingDetailObj.voiceToen,
      evalMode: 'sentence', // 句子
      format: 'mp3', //音频格式，有效值 aac/mp3
      scoreCoeff: 2.5 // 难度，4最高
    }
    manager.start(options); // 开始识别
  },

   // 评估模式
   getEvaluationMode(){
    const words = this.data.followUpReadingDetailObj.voiceToen;
    return words.includes(' ') ? 1:0
  },

  // 签到 
  saveSignIn: function () {
    commonAPI.signInSaveSignIn({}).then(res => {
      if (res.code == '200' && res.data) {
        FN.Toast(res.data);
      }
    })
  },

  // 录音测评结果解析 
  analysisTool: function (res) {
    var that = this;
    var obj = { voiceResultInfo: res, voiceResultAIModel: '1' }
    const { voiceResultInfo, oldWords } = that.formatWord(that.data.followUpReadingDetailObj.voiceToen, obj);
    var btnObjState = "btnimgarr[2]";
    var scoreDetailObj = "scoreDetail.voiceResultId";
    var voiceResultAIModel = "followUpReadingDetailObj.voiceResultAIModel";// AI模型
    var hwObj = "followUpReadingDetailObj.voiceResultAccuracy";
    var repeatTimes = "followUpReadingDetailObj.repeatTimes";
    var tempFilePath = "followUpReadingDetailObj.tempFilePath";
    var repeatResultInfo = "followUpReadingDetailObj.voiceResultInfo";
    that.setData({
      [voiceResultAIModel]: '1',
      [hwObj]: that.getaverage(res),
      scoreDetail: res,
      [scoreDetailObj]: that.data.followUpReadingDetailObj.voiceResultId,
      [tempFilePath]: res.tempFilePath,
      [repeatResultInfo]: voiceResultInfo,
      [btnObjState]: 1,
      [repeatTimes]: that.data.followUpReadingDetailObj.repeatTimes == null ? 1 : ++that.data.followUpReadingDetailObj.repeatTimes
    });
  },

  // 录音测评结果解析 
  analysisTool4SOE: function (res) {
    var that = this;
    var obj = { voiceResultInfo: res, voiceResultAIModel: '2' }
    const { voiceResultInfo, oldWords } = that.formatWord(that.data.followUpReadingDetailObj.voiceToen, obj);
    var btnObjState = "btnimgarr[2]";
    var tempFilePath = that.data.followUpReadingDetailObj.tempFilePath;
    var scoreDetailObj = "scoreDetail.voiceResultId";
    var voiceResultAIModel = "followUpReadingDetailObj.voiceResultAIModel";// AI模型
    var hwObj = "followUpReadingDetailObj.voiceResultAccuracy";// 跟读分数
    var repeatTimes = "followUpReadingDetailObj.repeatTimes";// 跟读次数
    var repeatResultInfo = "followUpReadingDetailObj.voiceResultInfo";// 跟读结果    
    that.setData({
      [voiceResultAIModel]: '2',
      [hwObj]: res.PronAccuracy.toFixed(1),//当为句子模式时，是所有已识别单词准确度的加权平均值
      scoreDetail: { ...that.data.tempFile, ...res },
      [tempFilePath]: res.tempFilePath,
      [scoreDetailObj]: that.data.followUpReadingDetailObj.voiceResultId,
      [repeatResultInfo]: {...voiceResultInfo,...that.data.tempFile},
      [btnObjState]: 1,
      [repeatTimes]: that.data.followUpReadingDetailObj.repeatTimes == null ? 1 : ++that.data.followUpReadingDetailObj.repeatTimes
    });
  },

// 有跟读结果的，文本依旧保留原有文字，只是改变颜色而已 
formatWord(oldWordStr, item) {
  const oldWords = oldWordStr.trim().split(/\s+/);
  const voiceResultInfo = typeof item.voiceResultInfo =='string' ? JSON.parse(item.voiceResultInfo):item.voiceResultInfo;
  if(item.voiceResultAIModel == '1'){
    voiceResultInfo.result.words.forEach((wordObj, index) => {
      if (oldWords[index]) {
        wordObj.word = oldWords[index];
      }
    });
  }else{
    voiceResultInfo.Words.forEach((wordObj, index) => {
      if (oldWords[index]) {
        wordObj.Word = oldWords[index];
      }
    });
  }
  return {voiceResultInfo,oldWords}
},

  noRepeat: function () {
    FN.Toast('请先跟读')
  },

  // 切换选项卡
  switchTab: function (ev) { // 如果id 为1:英文，2：翻译，3解析var id = e
    this.setData({
      swiperIndex: ev.target.dataset.id,
      currentItem: ev.target.dataset.id
    })
  },

  listenSwiperTab: function (ev) {
    this.setData({
      currentItem: ev.detail.current,
      swiperIndex: ev.detail.current
    })
  },

  // 查看纠音集
  correctHistory: function () {
    var that = this;
    var vsId = that.data.followUpReadingDetailObj.voiceSystemId,
      vsTitle = that.data.followUpReadingDetailObj.voiceToen;
    wx.navigateTo({
      url: '../correctGather/correctGather?vsId=' + vsId + '&vsTitle=' + vsTitle
    })
  },

  // 返回首页
  gohome: function () {
    wx.navigateBack({
      url: 'pages/index/index'
    })
  },

  // 查看评分详情 
  scoreDetail(e) {
    var that = this;
    const vrObj = {
      ...that.data.followUpReadingDetailObj
    };
    wx.navigateTo({
      url: '../sentence/sentence',
      events: {
        // 为指定事件添加一个监听器 ，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { vrObj })
      }
    })
  },

  // 计算用户的平均分 toFixed
  getaverage: function (res) {
    var total = 0,
      average = 0;
    res.result.words.map(function (item, i, arr) {
      total += item.pron_accuracy == -1 ? 0 : item.pron_accuracy
    })
    average = (total / res.result.words.length).toFixed(1);
    return average;
  },

  // 上传录音到七牛
  subVoiceInfo: function () {
    var that = this, filePath = that.data.evaluationType == '1' ? that.data.scoreDetail.tempFilePath:that.data.tempFile.tempFilePath, fileName = new Date().getTime() + ".mp3", 
    data = {
      "arenaId":that.data.followUpReadingDetailObj.hasOwnProperty('arenaId')?that.data.followUpReadingDetailObj.arenaId:null,
      homeworkId: null,
      voiceResultAccuracy: that.data.evaluationType == '1' ? that.getaverage(that.data.scoreDetail) : that.data.scoreDetail.PronAccuracy.toFixed(1),
      "voiceSystemId": that.data.followUpReadingDetailObj.voiceSystemId,
      "bookId": that.data.followUpReadingDetailObj.booksId,
      integralReq:{integralId:that.data.integralObj.integralId},
      voiceResultInfo: JSON.stringify(that.data.scoreDetail),
      voiceResultAIModel:that.data.evaluationType,// AI纠音模型
      voiceResultEvalMode:this.getEvaluationMode(),// 评估模式 
      integraldetailReq:{
        integralDetailType:that.data.pointsConfig4AIErrorCorrection.pointsConfigType,
        integralDetailDesc:that.data.pointsConfig4AIErrorCorrection.pointsConfigName,
        integralDetailNum:that.data.pointsConfig4AIErrorCorrection.pointsConfigType === "1" ? that.data.pointsConfig4AIErrorCorrection.pointsConfigValue : -that.data.pointsConfig4AIErrorCorrection.pointsConfigValue
      },
    };
    util.initQiniu();
    // 向七牛云上传
    util.qiniuUploaderUpload(filePath,fileName,(res)=>{
      data.myVoiceurl = res.fileURL;
      that.saveVoiceInfo(data);
    })
  },

  // 提交跟读者语音信息 保存用户的平均分
  saveVoiceInfo: function (data) {
    var that = this;
    commonAPI.vrSaveVoiceResult({ ...data }).then(res => {
      if (res.code == '200') {
        var scoreDetailObj = "scoreDetail.voiceResultId"
        that.setData({
          [scoreDetailObj]: res.data
        })
      }
    })
  },

  // 单个语音 查询是否已跟读过需要验证是否登录过
  hasRepeate: function (vsId) {
    var that = this
    commonAPI.vrHasRepeate({ voiceSystemId: vsId }).then(res => {
      if (res.code == '200') {
        var obj = res.data;
        const oldWords = obj.vs[0].voiceToen.trim().split(/\s+/);
        that.setData({
          words:oldWords
        })
        // 已经跟读过这条语音，直接展示最新跟读的信息。 scoreDetail
        if (obj.vrList.length > 0) { // 跟读过followUpReadingDetailObj
          var scoreDetailObj = "scoreDetail.voiceResultId",
            vrObj = obj.vrList[0];
          const voiceResultInfo = JSON.parse(vrObj.voiceResultInfo)
          vrObj.voiceResultInfo = voiceResultInfo
          that.setData({
            followUpReadingDetailObj: vrObj,
            scoreDetail: voiceResultInfo,
            [scoreDetailObj]: vrObj.voiceResultId
          })
          return ;
        }

        // 未跟读过
        if(obj.vs.length>0){
          that.setData({
            followUpReadingDetailObj: obj.vs[0],
          })
        }
       
      }
    })
  },

  // 生成海报
  createPoster() {
    var that = this;
    wx.getPrivacySetting({
      success: res => {
        if (res.needAuthorization) {
          wx.saveImageToPhotosAlbum({
            filePath: '',
            complete(r) {
              console.log("saveImageToPhotosAlbum:", r)
            }
          })
        } else {
          var voiceObj = that.data.followUpReadingDetailObj
          wx.navigateTo({
            url: '../makerPoster/studyPost/studyPost',
            events: {
              // 为指定事件添加一个监听器 ，获取被打开页面传送到当前页面的数据
              acceptDataFromOpenedPage: function (data) {
                console.log(data)
              },
              someEvent: function (data) {
                console.log(data)
              }
            },
            success: function (res) {
              // 通过 eventChannel 向被打开页面传送数据
              res.eventChannel.emit('acceptDataFromOpenerPage', { voiceObj })
            }
          })
        }
      },
      fail: () => { },
      complete: () => { }
    })
  },

  // 去到书本页面 booksid
  goChapterDetail: function (e) {
    var booksId = e.currentTarget.dataset.booksid;
    wx.navigateTo({
      url: '../myBooksChapter/myBooksChapter?booksId=' + booksId
    })
  },

  /** 
   * 此功能需要升级,进入homeworkrepeat所有的voiceResultInfo 都需要JSON.parse处理成对象型
  */
  intoPageType(options){
    const that = this;
      if(typeof options.scene == 'string'){
        that.hasRepeate(options.scene);
      }else{ // 跟读过
        options.scene.voiceResultInfo = typeof options.scene.voiceResultInfo == 'string' ? JSON.parse(options.scene.voiceResultInfo):options.scene.voiceResultInfo
        const repeatedInfo = options.scene;
        this.setData({
          followUpReadingDetailObj:repeatedInfo
        })
        const { voiceResultInfo, oldWords } = this.formatWord(repeatedInfo.voiceToen,repeatedInfo)
        this.setData({
          words:oldWords
        })
      }
  },

  // 去到擂台排行榜
  areaRanking: function () {
    var that = this;
    wx.navigateTo({
      url: '../arena/arena?scene=' + that.data.followUpReadingDetailObj.arenaId
    })
  },

  // 去到挑战赛
  goChallenge: function () {
    var that = this;
    wx.navigateTo({
      url: '../challenge/challenge?scene=' + that.data.options.challengeId
    })
  },

  // 初始化测评模型
  initManagerModel() {
    if (this.data.evaluationType == '1') {
      manager = plugin.getRecordRecognitionManager()// 智聆口语测评
    } else {
      this.initTengxunSOE();// 腾讯云智聆语音测评初始化
    }
  },

  // 初始化智聆语音测评（收费模式）
  initTengxunSOE() {
    var that = this;
    commonAPI.getFederationToken({}).then(res => {
      if (res.code == '200') {
        var obj = JSON.parse(res.data)
        var data = obj.Credentials;
        manager = plugin4SEO.getSoeRecorderManager({
          getAuthorization: function (callback) {
            callback({
              TmpSecretId: data.TmpSecretId,
              TmpSecretKey: data.TmpSecretKey,
              Token: data.Token
            });
          }
        });
        manager.onStart((res) => {
          console.log("成功开始录音识别", res)
        });

        /*
        识别结束事件,获取拿到音频数据
        1. 识别结束后，有*，需要处理。
        */
        manager.onStop((res) => {
          console.log("识别结束事件", res)
          that.setData({
            tempFile: res
          });
        })

        manager.onSuccess((res) => {
          console.log('打印识别结果', res)
          if (res.Status == "Finished") {
            that.analysisTool4SOE(res);
            that.subVoiceInfo(); // 同步录音到服务器
            that.saveSignIn(); // 签到
          }
        })

        manager.onError((res) => {
          //打印错误
          console.log('打印错误', res)
          // FN.Toast(res.Response.Error.Message);
          manager.stop();
        })
      }
    });
  },

 // 测评模式切换
 onChange4evaluationType(event){
  this.setData({
    evaluationType: event.detail
  });
  this.initManagerModel();
},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    let title;

    if (res.from === 'menu') {
      title = '每天5分钟，智能测评让你进步更快';
    }
    return {
      title: title,
      path: 'pages/homeworkrepeat/homeworkrepeat?scene=' + that.data.followUpReadingDetailObj.voiceSystemId,
    }
  },

  onShow: function (res) {
    var that = this;
    this.initManagerModel();
    app.setPageTabBarBadge(); //实时更新主菜单我的消息数字
    app.callbackSignIntegralInfo = res=>{
      that.setData({
        integralObj: res.userInfo.integralObj,
      })
      if(res.userInfo.integralObj.integralNum < this.data.pointsConfig4AIErrorCorrection.pointsConfigValue || res.userInfo.integralObj.integralNum==null){
        that.navigateToPointsPageForVideo(res.userInfo.integralObj.integralNum);
        return;
      }
    }
  },

// 跳转观看视频获取积分页面
navigateToPointsPageForVideo(integralNum){
  let promise = FN.Confirm(`当前积分：${integralNum?integralNum:0}，看视频可以获取40积分，是否观看？`);
  promise.then(res => {
    wx.navigateTo({
      url: '../myIntegral/myIntegral'
    })
  }).catch(res => {

  });
},
})